package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    StockMapper stockMapper;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        List<Long> buyProductIds = createOrderContext.getBuyProductIds();

        if (CollectionUtils.isEmpty(buyProductIds)) {
            buyProductIds = cartProductDtoList.stream().map(u -> u.getProductId()).collect(Collectors.toList());
        }
        buyProductIds.sort(Long::compareTo);

        List<Stock> stockList = stockMapper.findStocksForUpdate(buyProductIds);

        if (CollectionUtils.isEmpty(stockList)) {
            throw new BizException("库存未初始化");
        }
        if (stockList.size() != buyProductIds.size()) {
            throw new BizException("部分库存未初始化");
        }
        for (CartProductDto cartProductDto : cartProductDtoList) {
            Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();
            Long limitNum = cartProductDto.getLimitNum();

            Stock currentItem = stockMapper.selectStock(cartProductDto.getProductId());
            if (currentItem.getStockCount() < productNum) {

                redissonClient.getMap("orderErrorMap").put(createOrderContext.getUserId(), SysRetCodeConstants.STOCK_COUNT_ERROR.getCode());

                return false;
            }

            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);

            stockMapper.updateStock(stock);
        }
        return true;


    }
}